package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.UUID;
import java.io.File;

/**
 * @author JA
 * @date: 2025/5/5
 * description:图片上传接口
 */
@WebServlet("/api/upload/image")
public class ImageUploadServlet extends HttpServlet {
    // 本地图片保存目录
    private static final String IMAGE_UPLOAD_DIR = "/upload/images/";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 获取上传文件
        Part filePart = req.getPart("image");
        if (filePart == null || filePart.getSize() == 0) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("未上传图片"));
            return;
        }

        // 获取文件名后缀
        String fileName = filePart.getSubmittedFileName();
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileExt;

        // 获取上传路径（你需要确保该目录真实存在）
        String realPath = req.getServletContext().getRealPath(IMAGE_UPLOAD_DIR);
        File dir = new File(realPath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                ServletUtil.writeJsonResponse(resp, JsonResponse.error("目录创建失败"));
                return;
            }
        }

        // 保存文件
        File savedFile = new File(dir, newFileName);
        filePart.write(savedFile.getAbsolutePath());

        // 构造图片访问 URL
        String imageUrl = req.getContextPath() + IMAGE_UPLOAD_DIR + newFileName;
        ServletUtil.writeJsonResponse(resp, JsonResponse.success("上传成功", imageUrl));
    }
}
